package test.Bean;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.util.*;

public class DAO {
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	private ResultSet rs = null;
	
	
	private Connection getConnection() throws Exception{
		Context ctx = new InitialContext();
		Context env = (Context)ctx.lookup("java:comp/env");
		DataSource ds = (DataSource)env.lookup("jdbc/weekdb");
		return ds.getConnection();
	}
	
	public void insert(DTO dto) throws Exception{
		conn = getConnection();
		String sql = "insert into test values(?,?,?,sysdate)";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, dto.getId());
		pstmt.setString(2, dto.getPw());
		int age = Integer.parseInt(dto.getAge());
		//pstmt.setInt(3, dto.getAge());
		pstmt.setInt(3, age);
				
		pstmt.executeQuery();
		pstmt.close();
		conn.close();
		
	
	}
	
	public ArrayList<DTO> select(){
		ArrayList<DTO> list = new ArrayList();
		try{
			conn = getConnection();
			String sql="select * from test";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			DTO dto = null;
			while(rs.next()){
				dto = new DTO();
				dto.setId(rs.getString("id"));
				dto.setPw(rs.getString("pw"));
				dto.setAge(rs.getString("age"));
				dto.setReg(rs.getTimestamp("reg"));
				list.add(dto);

			}
			
			
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			try{rs.close();}catch(SQLException e){}
			try{pstmt.close();}catch(SQLException e){}
			try{conn.close();}catch(SQLException e){}
		}
		return list;
	}
	
	
	
}
